import sys
import os
from datetime import timedelta

from django.contrib.auth import authenticate

from base_db import Influxdb_info
# from models import InfluxInfo
from orm import regestUserName

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from django.shortcuts import render, HttpResponse, redirect
from createData import add_db, search_db, delete_db
from config import get_json_data, modify_json_data, get_json_sql, recordsql, updateSqlList
from runclish import runclish
from modsim import change_modbus_value
from django.http import JsonResponse
from func import *
from influxdbHome.models import Department, UserInfo,InfluxInfo


def orm(request):
    # 新增数据
    # Department.objects.create(title='销售部')
    UserInfo.objects.create(name='xiaoming', password='123e', age='19')

    # 删除  filter是筛选
    # Department.objects.filter(id=3).delete()
    # 删除所有
    # Department.objects.all().delete()

    # 获取数据 QuerySet类型 [行，行， 行]

    # data_list = Department.objects.all()
    # for obj in data_list:
    #     print(obj.title)
    # 一个行也是 Queryset
    # data_list = Department.objects.filter(id=1)
    # print(data_list)
    # 获取第一条数据[对象]
    # row_obj = Department.objects.filter(id=1).first()
    # print(row_obj.title)

    # 更新数据
    # 更新所有
    # Department.objects.all().update(title='IT')
    # 更新一个
    # Department.objects.filter(id = 2).update(title='技术')

    return HttpResponse('成功')


def info_list(request):
    data_list = UserInfo.objects.all()
    print(data_list)
    return render(request, 'info_list.html', {'data_list': data_list})


# Create your views here

def user_list(request):
    name = "xiaoli"
    role = ["gly", "baoan", "student"]
    n3 = {"name": "小明", "age": 21, "role": "student"}
    return render(request, "user_list.html", {"n1": name, "role": role, "n3": n3})


def something(req):
    # request 是一个对象， 封装了用户通过发过来的所有请求相关数据
    # 获取请求方式GET/POST
    print(req.method)
    print(req.GET)
    return HttpResponse("something")
    # return redirect("http://www.baidu.com")


def influxdb(req):
    user_name = req.session.get('mykey')
    if user_name == None:
        return redirect('/login/')
    sqlresult = get_json_sql(user_name)
    if req.method == "GET":
        data = get_json_data(user_name)
        return render(req, "influxdb.html", {"data": data, "sqls": sqlresult, 'user_name': user_name})
    post = req.POST
    IP = post.get("IP")
    sql = post.get('sql')
    pid = post.get("PID")
    default = {"IP": IP, "sql": sql, "PID": pid}

    # 更新基本信息默认值
    modify_json_data(user_name, **default)
    # 获取最新基本信息
    data = get_json_data(user_name)
    costtime = runclish(user_name, sql)
    # 更新数据库语句list
    needupdate = recordsql(sql, user_name)
    if needupdate:
        updateSqlList(sql, user_name)
    first, end, listNum, errorinfo = search_from_file()

    return render(req, "influxdb.html",
                  {"data": data, "listNum": listNum, "first": first, "end": end, "errorinfo": errorinfo,
                   "sqls": sqlresult,
                   "costtime": costtime, 'user_name': user_name})


def influx2(req):
    user_name = req.session.get('mykey')
    if user_name == None:
        return redirect('/login/')
    if req.method == "GET":
        data = get_json_data(user_name)
        lines = get_lines()
        return render(req, "influx2.html", {"data": data, "lines": lines, 'user_name': user_name})
    data = get_json_data(user_name)
    db_info = Influxdb_info()
    influxDB_name = db_info.get_influxDB_name()
    influxDB_table = db_info.get_influxDB_table()
    password_db = db_info.get_influxDB_password()

    post = req.POST
    print(post)
    IP = post.get("IP")
    PID = post.get("PID")
    IDS = post.get("IDS")
    StartTime = post.get("StartTime")
    Days = post.get("Days")
    Hours = post.get("Hours")
    Minutes = post.get("Minutes")
    Seconds = post.get("Seconds")
    DataType = post.get("DataType")
    BaseNumber = post.get("BaseNumber")
    Range = post.get("Range")
    Step = post.get("Step")
    SubmitType = post.get("Submit")
    print(post.get("ifAdd"))
    ifAdd = 0 if post.get("ifAdd") == None else 1
    print(SubmitType)
    # 修改默认值
    default = {"IP": IP, "PID": PID, "IDS": IDS, "StartTime": StartTime, "Days": Days, "Hours": Hours,
               "Minutes": Minutes, "Seconds": Seconds, "DataType": DataType,
               "BaseNumber": BaseNumber, "Range": Range, "Step": Step, "SubmitType": SubmitType, "ifAdd": ifAdd}
    modify_json_data(user_name, **default)
    if SubmitType == "CreateDB":

        data = get_json_data(user_name)
        add_db.create_num(IP, PID, IDS, StartTime, Days, Hours, Minutes, Seconds, DataType, BaseNumber, Range, ifAdd,
                          Step)
        first, end, listNum, lines = search_from_file_simple()
    elif SubmitType == "SearchDB":
        search_db.search_num(IP, PID, IDS)
        # 从searchResult.txt中读取信息
        first, end, listNum, lines = search_from_file_simple()
        data = get_json_data(user_name)
    else:
        delete_db.delete_num(IP, PID, IDS)
        first, end, listNum, lines = search_from_file_simple()
        data = get_json_data(user_name)
    return render(req, "influx2.html",
                  {"data": data, "first": first, "end": end, "listNum": listNum, "lines": lines,
                   'user_name': user_name})


def modsim(req):
    user_name = req.session.get('mykey')
    if user_name == None:
        return redirect('/login/')
    if req.method == "GET":
        data = get_json_data(user_name)
        lines = get_lines()
        return render(req, "modsim.html", {"data": data, "lines": lines, 'user_name': user_name})
    post = req.POST
    print(post)
    ModsimIP = post.get("ModsimIP")
    ModsimPort = post.get("ModsimPort")
    ModsimAddress = post.get("ModsimAddress")
    ModsimType = post.get("ModsimType")
    ModsimNumber = post.get("ModsimNumber")
    SubmitType = post.get("Submit")
    print(SubmitType)
    # 修改默认值
    default = {"ModsimIP": ModsimIP, "ModsimPort": ModsimPort, "ModsimAddress": ModsimAddress, "ModsimType": ModsimType,
               "ModsimNumber": ModsimNumber, "SubmitType": SubmitType}
    modify_json_data(user_name, **default)
    data = get_json_data(user_name)
    change_modbus_value(ModsimIP, ModsimPort, ModsimAddress, ModsimType, ModsimNumber)
    return render(req, "modsim.html",
                  {"data": data, 'user_name': user_name})


def login(req):
    return render(req, 'login.html')


def check(req):
    # 获取用户提交的数据
    # req.session.clear()
    # exp_time = timedelta(days=2)
    # request.session.set_expiry(exp_time)
    # my_data = request.session.get('mykey')

    post = req.POST
    name = post.get('name')
    # password = post.get('pwd')
    print(name)
    # print(password)
    # 判断用户名是否合法
    if name != '':
        # 将用户名添加到session中
        req.session['mykey'] = name
        # 获取session中的名字
        user_name = req.session.get('mykey')

        # ORM 数据库方法，注册用户，设置默认值
        checkname = InfluxInfo.objects.filter(Name=name).first()
        if checkname == None:
            print('注册用户名，给默认值')
            regestUserName(name)



        data = get_json_data(user_name)
        lines = get_lines()
        return redirect("/modsim", {"data": data, "lines": lines})
    else:
        return redirect('/login')


# 注销登录session
def removeSession(req):
    req.session.clear()
    response_data = {'message': 'Hello, World!'}  # 示例数据
    return JsonResponse(response_data)
    # return redirect("/modsim")


# 快速更改modbus值，模拟真实场景
def qcmodsim(req):
    user_name = req.session.get('mykey')
    if user_name == None:
        return redirect('/login/')
    if req.method == "GET":
        data = get_json_data(user_name)
        lines = get_lines()
        return render(req, "quick_change_modsim.html", {"data": data, "lines": lines, 'user_name': user_name})
    post = req.POST
    print(post)
    print("1111")
